﻿using System.Linq;
using Newtonsoft.Json.Linq;
using RecognitionForm.Handler;
using System;
using System.Collections.Generic;
using System.IO;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace RecognitionForm
{
    public class PersonWebSocketBehavior : WebSocketBehavior
    {
        DataProvider dataProvider = new DataProvider();

        protected async override void OnOpen()
        {
            var initPersons = await dataProvider.SynchronizePerson();
            Send(initPersons);
        }

        protected override void OnMessage(MessageEventArgs e)
        {
            string saveStr = "";
            var request = e.Data.DeserializeObject<dynamic>();
            if (request is string || request is long)
            {
                Send(request);
            }

            if (request.sid == null)
            {
                return;
            }

            string sid = Convert.ToString(request.sid);
            switch (sid)
            {
                case "bms.boss.recognition.upload":
                    if (request.payload != null && request.payload.paramList != null)
                    {
                        var paramList = (request.payload.paramList as IEnumerable<dynamic>).ToList();
                        paramList.ForEach(p =>
                        {
                            saveStr += dataProvider.GetStaffName(Convert.ToString(p.code)).Result + ",";
                        });
                        saveStr = saveStr.TrimEnd(',');
                    }

                    //保存识别结果到目录
                    var path = @"C:\DMB-BS3.2.02.38447-finance-win-x86\dmb\ftpserver\home\person\";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    using (var sw = new StreamWriter(Path.Combine(path, "content.txt"), false))
                    {
                        sw.WriteLine(saveStr);
                        sw.Close();
                    }

                    Console.WriteLine(saveStr);

                    var response = dataProvider.Recognition();
                    Send(response);
                    break;

                case "ems.common.person.synchronize":
                    if (request.code == "00000000")
                    {
                        Console.WriteLine("人员登记成功");
                    }
                    else
                    {
                        Console.WriteLine(request.message);
                    }
                    break;
            }

        }
    }
}
